import axios from 'axios';
import { getNested } from '@/utils/util';
import { requestConfig } from '@/utils/interceptor';

const service = axios.create({
  baseURL: '',
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
  timeout: 5000 // 设置请求超时时间
});
// request拦截器
service.interceptors.request.use(
  config => {
    // GET请求
    if (config.method === 'get' && config.data) {
      const { data } = config;
      Object.entries(data).forEach(([key, value]) => {
        if (config.url.includes('?')) {
          config.url += `&${key}=${value}`;
        } else {
          config.url += `?${key}=${value}`;
        }
      });
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      const code = getNested(response, 'data', 'code');
      if (code !== 0) {
        return Promise.reject(response.data);
      }
    }
    return response.data;
  },
  async error => {
    console.log(error, 'error');
    const status = error.response?.status;
    const { url } = error.config;
    if (status === 401) {
      /* empty */
    }
    if ([403].includes(status)) {
      /* empty */
    }
    error.msg = error.response?.data?.msg; // 自定义错误信息
    return Promise.reject(error);
  }
);
export default service;
